#include <pcap.h>
#include <stdio.h>
#include <netinet/ip.h>
#include <arpa/inet.h>

#define MAX_PACKETS 100

void packet_handler(u_char *user, const struct pcap_pkthdr *pkthdr, const u_char *packet) {
    static int packet_count = 0;

    if (packet_count < MAX_PACKETS) {
        struct ip *ip_header = (struct ip *)(packet + 14);  // Assuming Ethernet frame

        char source_ip[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &(ip_header->ip_src), source_ip, INET_ADDRSTRLEN);

        printf("Packet %d - Source IP: %s\n", packet_count + 1, source_ip);

        packet_count++;
    }
}

int main() {
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *handle;

    // Open the default network interface (change as needed)
    handle = pcap_open_live("eth0", BUFSIZ, 1, 1000, errbuf);

    if (handle == NULL) {
        printf("Error opening device: %s\n", errbuf);
        return 1;
    }

    // Set a packet filter (optional)
    struct bpf_program fp;
    char filter_exp[] = "ip";  // Filter for IP packets
    if (pcap_compile(handle, &fp, filter_exp, 0, PCAP_NETMASK_UNKNOWN) == -1) {
        printf("Error compiling filter\n");
        return 1;
    }
    if (pcap_setfilter(handle, &fp) == -1) {
        printf("Error setting filter\n");
        return 1;
    }

    pcap_loop(handle, 0, packet_handler, NULL);

    pcap_close(handle);

    return 0;
}
